//
//  JCLEmoticonCell.swift
//  表情键盘
//
//  Created by DDC on 2017/9/27.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit

// 设置代理
@objc protocol JCLEmoticonCellDelegate:NSObjectProtocol {
    
    /// 代理方法
    ///
    /// - Parameters:
    ///   - cell: self
    ///   - emo: emo模型
    func emoticonCellDidSelectedEmoticon (cell:JCLEmoticonCell,emo:JCLEmoticon?)
}
class JCLEmoticonCell: UICollectionViewCell {

    // 代理属性
    weak var delegate:JCLEmoticonCellDelegate?
    // emoji 模型
    var emoticons:[JCLEmoticon]? {
        didSet {
            
            // 隐藏之前所有的按钮
            for v in contentView.subviews {
                v.isHidden = true
            }
            contentView.subviews.last?.isHidden = false
            // 遍历数组,加载数据显示按钮图片
            for (i,emo) in (emoticons ?? []).enumerated() {
                
                if let btn = contentView.subviews[i] as? UIButton {
                
                    btn.setImage(emo.image, for: [])
                    btn.setTitle(emo.emojiStr, for: [])
                    btn.isHidden = false
                }
            }
        }
    }
    
    // 懒加载提示图片视图
    fileprivate lazy var tipView = JCLEmoticonTipView()
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // 将提示视图添加到窗口上 ，用以显示出其完整的视图
    override func willMove(toWindow newWindow: UIWindow?) {
        super.willMove(toWindow: newWindow)
        guard let w = newWindow else {
            return
        }
        w.addSubview(tipView)
        tipView.isHidden = true
    }
}

// MARK: - 纯代码加载每页cell的显示内容
fileprivate extension JCLEmoticonCell {
    func setupUI() {
        // 设置常量
        let rowCount = 3
        let colCount = 7
        let leftMargin:CGFloat = 8
        let bottomMargin:CGFloat = 16
        let width = (bounds.width - 2 * leftMargin) / CGFloat(colCount)
        let height = (bounds.height - bottomMargin) / CGFloat(rowCount)
        for i in 0..<21 {
            let row = i / colCount
            let col = i % colCount
            let btn = UIButton()
            // 设置按钮的大小
            let x = leftMargin + CGFloat(col) * width
            let y = CGFloat(row) * height
            btn.frame = CGRect(x: x, y: y, width: width, height: height)
            // 设置emoji表情的字体大小
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
            // 添加到视图上
            contentView.addSubview(btn)
            // 设置button的tag值
            btn.tag = i
            btn.addTarget(self, action: #selector(selectedEmoticonButton), for: .touchUpInside)
        }

        let btn = contentView.subviews.last as! UIButton
        let image = UIImage(named: "delete")

        btn.setImage(image, for: [])
        
        // 给按钮添加长按手势
        let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPressTouch))
        longPress.minimumPressDuration = 0.1
        addGestureRecognizer(longPress)
        
    }
    /// 手势识别方法
    ///
    /// - Parameter gesture: 长按手势
    @objc func longPressTouch(gesture:UILongPressGestureRecognizer) {
        
        // 添加提示图片--只会在collection中显示，超出界面不显示 ↑↑->（willMoveToWindow）
        // addSubview(tipView)
        // 获取触摸位置
        let location = gesture.location(in: self)
        
        guard let button = buttonWithLocation(location: location) else {
            tipView.isHidden = true
            return
        }
        // 根据tag值来设置模型
        if button.tag < (emoticons?.count)! {
            tipView.emoticon = emoticons?[button.tag]
        }
        // 根据手势的状态来设置提示视图的显示状态
        switch gesture.state {
        case .began,.changed:
            tipView.isHidden = false
            // 设置位置
            // 将按钮的位置转换到window上
            let center = self.convert(button.center, to: window)
            tipView.center = center
        case .ended:
            tipView.isHidden = true
            // 将所选按钮加载到视图中
            selectedEmoticonButton(button: button)
        case .cancelled,.failed :
            tipView.isHidden = true
        default:
            break
        }
    }
    
    // 根据触摸事件创建点击的按钮
    func buttonWithLocation(location:CGPoint)->UIButton? {
        // 遍历子视图
        for btn in contentView.subviews as! [UIButton] {
            // 根据手势的位置来加载出按钮的视图位置
            if !btn.isHidden && btn != contentView.subviews.last && btn.frame.contains(location) {
                return btn
            }
        }
        return nil
    }
    
    // MARK:  - 点击事件
    @objc func selectedEmoticonButton (button:UIButton) {
        
        let idx = button.tag
        var emo:JCLEmoticon?
        if idx < (emoticons?.count)! {
            emo = emoticons?[idx]
        }
        print(emo)
        delegate?.emoticonCellDidSelectedEmoticon(cell: self, emo: emo)
        
    }
}
